package org.hhttp.core;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;


public class Listener extends ServerSocket{

	private static Logger logger = Logger.getLogger(Listener.class);
	
	Chain chain;
	private boolean flag = false; 
	public Listener() throws IOException {
		super();
	}
	public Listener(int port) throws IOException {
		super(port);
	}
	
	public void init(){
		//TODO 初始化
	}
	
	public void start(){
		try{
	        System.out.println("The WebServer is listening on port "+this.getLocalPort());
	        startListener();
	        chain = new Chain(  
	        		Constants.thread_pool_initnum,
	        		Constants.thread_pool_maxnum, 
	        		Constants.thread_pool_keepalivetime, 
	                TimeUnit.MINUTES,   //unit  
	                new ArrayBlockingQueue<Runnable>(3)  
	        );   
	        int i = 0;
	        Socket clientSocket = null; 
	        while(flag){
	        	try {
	        		clientSocket = accept();
		        	chain.execute(new Handler("task" + i++,clientSocket));
				} catch (Exception e) {
					logger.error("client Socket accept error " + e);
				}
	        }
	    }catch(Exception e){
	    	logger.error("hhttp start error " + e);
	    }
	}
	public void startListener(){  
		this.flag = true;
	}
	
	public void stopListener(){  
		this.flag = false;
	}

}
